package com.eolcum.evo.service;

import java.io.IOException;
import java.util.Calendar;

import com.eolcum.evo.persistence.DataBaseHelper;
import com.eolcum.evo.persistence.RTCLog;
import com.eolcum.evo.persistence.Sensor;
import com.eolcum.evo.thread.RoomTemperatureController;
import com.google.gson.Gson;

import android.app.Service;
import android.content.Intent;
import android.database.SQLException;
import android.os.IBinder;
import android.util.Log;

public class EvoLoggerService extends Service {

	private DataBaseHelper db;
	
	@Override
	public void onCreate() {
		super.onCreate();
		db = new DataBaseHelper(getApplicationContext());

		try {
			db.createDataBase();
		} catch (IOException ioe) {
			throw new Error("Unable to create database");
		}

		try {
			db.openDataBase();
		} catch (SQLException sqle) {
			throw sqle;
		}
	}
	
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		
		Log.i("LoggerService", "LoggerService starting...");
		if (intent.getAction() != null) {
			if (intent.getAction().equals("com.eolcum.evo.service.EvoLoggerService")) {
				Log.i("Receiver", "Bound to EvoService");
				if ("getSensor".equals(intent.getExtras().getString("function_name"))) {
					Gson gson = new Gson();
					Sensor sensor = gson.fromJson(intent.getExtras().getString("sensor"), Sensor.class);
					long sensorLogId = db.insertSensor(sensor);
					Log.i("sensorLogId", "" + sensorLogId);
				} else if ("logRTC".equals(intent.getExtras().getString("function_name"))) {
					Gson gson = new Gson();
					RoomTemperatureController rtc = gson.fromJson(intent.getExtras().getString("RTCLog"), RoomTemperatureController.class);
					RTCLog rtcLog  = new RTCLog();
					rtcLog.setActuatorOutput(rtc.getActiveOutput());
					rtcLog.setRoomId(rtc.getRoom().getId());
					rtcLog.setRoomTemperature(rtc.getActiveInput());
					rtcLog.setSetpoint(rtc.getRoom().getActualTemperatureSetpoint());
					rtcLog.setTimeStamp(Calendar.getInstance().getTimeInMillis());
					long rtcLogId = db.insertRTCLog(rtcLog);
					Log.i("rtcLogId", "" + rtcLogId);
				}
			}
		}		Log.i("LoggerService", "LoggerService started.");
		return super.onStartCommand(intent, flags, startId);
	}

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}
}